package javaSE.JDBC;

import java.sql.*;

public class jdbcDemo {
    public static String driverDriver = "com.mysql.jdbc.Driver";
    public static String url = "jdbc:mysql://localhost:3306/happygo";
    public static String user = "root";
    public static String password = "root";

    public static void main(String[] args) {
        User testUser = new User();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        String sql = "SELECT * FROM USER WHERE user_id=?";
        try {
            Class.forName(driverDriver);
            connection = DriverManager.getConnection(url, user, password);
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "4");
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                testUser.setUserName(resultSet.getString("user_name"));
                testUser.setUserId(resultSet.getString("user_id"));
            }
        } catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {

            try {
                if (resultSet != null && resultSet.isClosed()) {
                    resultSet.close();
                }
                if (preparedStatement != null && preparedStatement.isClosed()) {
                    preparedStatement.close();
                }
                if (connection != null && connection.isClosed()) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.out.println(e.getMessage());
            }


        }

        System.out.println(testUser);
    }
}

class User {
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    @Override
    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", userId='" + userId + '\'' +
                '}';
    }

    private String userName;
    private String userId;
}
